import CryptoJS from 'crypto-js'

const aeskey = 'gxwzlbcb9d11b3be25f5a1a7dc8ca0cd';

const install = (Vue, vm) => {

	Vue.prototype.$secret = {
		// AES 加密
		encryptAES(data, key) {
			if (!data || data === '') {
				return data;
			}
			if (!key || key === '') {
				key = aeskey;
			}
			// 处理密钥：转换为WordArray类型
			const secretKey = CryptoJS.enc.Utf8.parse(key)

			// 加密配置（使用CBC模式和Pkcs7填充）
			const cfg = {
				iv: CryptoJS.enc.Utf8.parse(key.slice(0, 16)), // 取前16位作为IV
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			}

			// 执行加密
			const encrypted = CryptoJS.AES.encrypt(
				CryptoJS.enc.Utf8.parse(data),
				secretKey,
				cfg
			)

			// 返回Base64格式的加密结果
			return encrypted.toString()
		},

		// AES 解密
		decryptAES(encryptedData, key) {
			if (!encryptedData || encryptedData === '') {
				return encryptedData;
			}
			if (!key || key === '') {
				key = aeskey;
			}
			const secretKey = CryptoJS.enc.Utf8.parse(key)
			const cfg = {
				iv: CryptoJS.enc.Utf8.parse(key.slice(0, 16)),
				mode: CryptoJS.mode.CBC,
				padding: CryptoJS.pad.Pkcs7
			}

			const decrypted = CryptoJS.AES.decrypt(
				encryptedData,
				secretKey,
				cfg
			)

			return decrypted.toString(CryptoJS.enc.Utf8)
		}
	}
}

export default {
	install
}